package com.gsc.controller;

import com.gsc.domain.ResponseResult;
import com.gsc.domain.dto.UserDto;
import com.gsc.domain.entity.Role;
import com.gsc.domain.entity.User;
import com.gsc.domain.vo.PageVo;
import com.gsc.domain.vo.UserInfoAndRoleIdsVo;
import com.gsc.exception.SystemException;
import com.gsc.service.RoleService;
import com.gsc.service.UserRoleService;
import com.gsc.service.UserService;
import com.gsc.utils.BeanCopyUtils;
import com.gsc.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author gscstart
 * @create 2023/2/23-10:34
 */
@RestController
@RequestMapping("/system/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;


    @GetMapping("/list")
    public ResponseResult selectUserList(Integer pageNum, Integer pageSize, User user){

        PageVo pageVos = userService.selectUserList(pageNum, pageSize, user);

        return ResponseResult.okResult(pageVos);
    }

    @PostMapping
    public ResponseResult addUser(@RequestBody UserDto userDto){
        return userService.addUser(userDto);
    }

    @DeleteMapping("/{id}")
    public ResponseResult deleteUser(@PathVariable("id") Long id){
        if(SecurityUtils.getUserId().equals(id)){
            return ResponseResult.errorResult(500,"不能删除当前操作的用户");
        }
        userService.removeById(id);
        return ResponseResult.okResult();

    }

    @GetMapping("/{id}")
    public ResponseResult selectUserById(@PathVariable("id") Long id){

        //查询所有的角色列表
        List<Role> roles = roleService.listAllRole();
        //查询当前用户信息
        User user = userService.getById(id);
        //当前用户所具有的的角色id列表
        List<Long> roleIds = userRoleService.selectRoleIdByUserId(id);

        UserInfoAndRoleIdsVo vo = new UserInfoAndRoleIdsVo(user,roles,roleIds);

        //封装vo返回
        return ResponseResult.okResult(vo);
    }

    @PutMapping
    public ResponseResult updateUser(@RequestBody UserDto userDto){

        userService.updateUser(userDto);



        return ResponseResult.okResult();
    }



}
